#include "trackmodel.h"

TrackModel::TrackModel(QObject *parent) :
    QAbstractListModel(parent)
{
    this->setRoleNames(TrackItem::roleNames());    
}

int TrackModel::rowCount(const QModelIndex &parent) const
{
    return _itens.count();
}

QVariant TrackModel::data(const QModelIndex &index, int role) const
{
    return (index.isValid() ? _itens[index.row()]->data(role) : QVariant());
}

void TrackModel::Marcar(int idRastreio, bool marcar)
{
    for (int i = 0; i < _itens.count(); i++) {
        if (_itens[i]->getIdRastreio() == idRastreio) {
            _itens[i]->setSelecionado(marcar);
            emit dataChanged(createIndex(i, 0), createIndex(i, 0));
            emit existemItensSelecionadosNotify();
            break;
        }
    }
}

void TrackModel::AtualizarTrack(int idTrack, const QString &description)
{
    for(int i = 0; i < _itens.count(); i++)
        if (_itens[i]->getIdRastreio() == idTrack) {
            _itens[i]->setDescription(description);
            emit trackAtualizado(idTrack, description);
            emit dataChanged(createIndex(i, 0), createIndex(i, 0));
            break;
        }
}

void TrackModel::RemoverTracksSelecionados()
{    
    int i = 0;
    while (i < _itens.count()) {
        if (_itens[i]->getSelecionado()) {
            emit removerTrack(_itens[i]->getIdRastreio());
            beginRemoveRows(QModelIndex(), i, i);
            _itens.removeAt(i);
            endRemoveRows();
        } else i++;
    }
    emit existemItensSelecionadosNotify();
    emit qtdItensNotify();
}

void TrackModel::AtualizarTracksSelecionados()
{
    for(int i = 0; i < _itens.count(); i++)
        if (_itens[i]->getSelecionado())
            emit atualizarTrackInternet(_itens[i]->getRastreio());
}

void TrackModel::adicionarTrack(TrackItem *item)
{
    beginInsertRows(QModelIndex(), _itens.count(), _itens.count());
    _itens.append(item);
    endInsertRows();
    emit qtdItensNotify();
}
